#include <timer.h>
#include <led.h>
#include <GPIO_Config.h>
/*
typedef struct
{
  __IO uint16_t CR1;
  __IO uint16_t CR2;
  __IO uint16_t SMCR;
  __IO uint16_t DIER;
  __IO uint16_t SR;
  __IO uint16_t EGR;
  __IO uint16_t CCMR1;
  __IO uint16_t CCMR2;
  __IO uint16_t CCER;

  __IO uint16_t CNT;
 
  __IO uint16_t PSC;

  __IO uint16_t ARR;

  __IO uint16_t RCR;

  __IO uint16_t CCR1;

  __IO uint16_t CCR2;

  __IO uint16_t CCR3;

  __IO uint16_t CCR4;

  __IO uint16_t BDTR;

  __IO uint16_t DCR;

  __IO uint16_t DMAR;

} TIM_TypeDef;
 */
void TIM3_IRQHandler(void)
{
	if(TIM3->SR & 0x0001)
		LED1 = !LED1;
	TIM3->SR &= (~0x0001);
}

//arr: auto-reload register
//psc: 时钟预分频
//TIM3是一个TIM_TypeDef类型的结构体指针
void TIM3_Int_Init(unsigned short arr, unsigned short psc)
{
	RCC->APB1ENR |= 0x02;
	TIM3->ARR = arr;
	TIM3->PSC = psc;
	TIM3->DIER |= 1;//使能更新中断，DIER：DMA/中断使能寄存器
	TIM3->CR1 |= 1;
	MY_NVIC_Init(1,3,TIM3_IRQn,2);
}

//PWM模式2表示 CNT > CCR 为有效电平
//比较时，根据CCER的配置，可以选OC是高电平有效或低电平有效
void TIM1_PWM_Init(unsigned short arr, unsigned short psc)
{
	RCC->APB2ENR |= 1<<11;
	GPIOA_Enable();
	GPIO_config(GPIOA,8,AF_PP);
	TIM1->ARR = arr;
	TIM1->PSC = psc;
	TIM1->CCMR1 |= 7<<4;	//CH1配置OC1M为111模式（PWM2），CC1S输出模式（默认）
	TIM1->CCMR1 |= 1<<3;	//使能CCR1预装载，读写CCR1只对预装载寄存器操作，在更新事件到来后预装载寄存器的值加载到CCR1
	TIM1->CCER |= 1;		//输出使能位，OC高电平有效
	TIM1->BDTR |= 1<<15;	//MOE主输出使能，通用寄存器不用这步
	TIM1->CR1 = 0x0080;		//使能ARR预装载，CMS配置为边沿对齐模式
	TIM1->CR1 |= 1;			//使能定时器
}
//捕获状态
//[7]:0,没有成功的捕获;1,成功捕获到一次.
//[6]:0,还没捕获到高电平;1,已经捕获到高电平了.
//[5:0]:捕获高电平后溢出的次数
unsigned char TIM2CH1_CAPTURE_STA=0;
unsigned short TIM2CH1_CAPTURE_VAL=0;
void TIM2_IRQHandler(void)
{
	unsigned short tsr;
	tsr = TIM2->SR;
	
}
//arr设置为0xFFFF应该会更好些
//TIM时钟频率应该是72MHz，
void TIM2_Cap_Init(unsigned short arr, unsigned short psc)
{
	GPIOA_Enable();
	GPIO_config(GPIOA,0,PD_In);//这两步可以通过KEY_Init()来做
	RCC->APB1ENR |= 0x01;
	
	TIM2->ARR = arr;
	TIM2->PSC = psc;
	TIM2->CCMR1 &= 0xFF00;
	TIM2->CCMR1 |= 0x11;	//输入模式，N=2
	TIM2->DIER |=0x03;		//允许通道1的CC中断和更新中断
	TIM2->CCER |=0x01;		//Enable cpature，bit1 = 0，上升沿捕获
	TIM2->CR1 |= 0x01;		//使能计数器
	MY_NVIC_Init(1,2,TIM2_IRQn,2);
}
